package com.tencreat.mall.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.tencreat.common.annotation.Log;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.controller.BaseController;
import com.tencreat.common.core.domain.AjaxResult;
import com.tencreat.common.core.domain.model.ReqIdParam;
import com.tencreat.common.core.domain.model.ReqIdsParam;
import com.tencreat.common.core.domain.model.ReqStringParam;
import com.tencreat.common.enums.BusinessType;
import com.tencreat.common.utils.StringUtils;
import com.tencreat.common.utils.poi.ExcelUtil;
import com.tencreat.domain.mall.MallCategory;
import com.tencreat.domain.mall.MallCouponUser;
import com.tencreat.domain.mall.MallGoods;
import com.tencreat.service.mall.IMallCategoryService;
import com.tencreat.service.mall.IMallGoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 类目Controller
 *
 * @author tencreat
 * @date 2021-08-15
 */
@Api(tags="类目api")
@RestController
@RequestMapping("/mall/category")
public class AdminMallCategoryController extends BaseController {
    @Autowired
    private IMallCategoryService mallCategoryService;

    @Autowired
    private IMallGoodsService mallGoodsService;

    /**
     * 查询类目列表
     */
    @ApiOperation(value="查询类目列表")
    @PreAuthorize("@ss.hasPermi('mall:category:list')")
    @PostMapping("/list")
    public HttpResult<IPage<MallCategory>> list(@RequestBody  MallCategory mallCategory) {
        LambdaQueryWrapper<MallCategory> wrapper = Wrappers.query(mallCategory).lambda();
        wrapper.eq(MallCategory::getPid, 0);
        wrapper.orderByAsc(MallCategory::getSortOrder);
        wrapper.orderByDesc(MallCategory::getSortUpdateTime);
        Page<MallCategory> page = new Page<>(mallCategory.getPageNum(), mallCategory.getPageSize());
        page = mallCategoryService.page(page, wrapper);
        if (page != null && page.getRecords() != null && page.getRecords().size() >0) {
            // 查询子类
            List<Long> pids = page.getRecords().stream().map(MallCategory::getId).collect(Collectors.toList());
            List<MallCategory> list = mallCategoryService.lambdaQuery().in(MallCategory::getPid, pids).orderByAsc(MallCategory::getSortOrder).list();
            if (list != null && list.size() > 0) {
                Map<Long,List<MallCategory>> categoryMap = list.stream().collect(Collectors.groupingBy(MallCategory::getPid));;
                page.getRecords().forEach(item->{
                    if (categoryMap.get(item.getId()) != null){
                        item.setChild(categoryMap.get(item.getId()));
                    }
                });
            }
        }

        return HttpResult.ok(page);
    }
    /**
     * 查询专区列表
     */
    @ApiOperation(value = "查询专区列表")
    @PreAuthorize("@ss.hasPermi('mall:category:goodlist')")
    //@PostMapping("/goodlist")
    public HttpResult<List<MallCategory>> list(@RequestBody ReqStringParam mallCategory) {
        LambdaQueryChainWrapper<MallCategory> wrapper = mallCategoryService.lambdaQuery();
        if (StringUtils.isNotBlank(mallCategory.getCommon())) {
            wrapper.like(MallCategory::getName, mallCategory.getCommon());
        }
        return HttpResult.ok(wrapper.orderByAsc(MallCategory::getSortOrder).list());
    }
    /**
     * 导出类目列表
     */
    @ApiOperation(value="导出类目列表")
    @PreAuthorize("@ss.hasPermi('mall:category:export')")
    @Log(title = "商品管理>商品分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(MallCategory mallCategory) {
        List<MallCategory> list = mallCategoryService.selectMallCategoryList(mallCategory);
        ExcelUtil<MallCategory> util = new ExcelUtil<MallCategory>(MallCategory.class);
        return util.exportExcel(list, "category");
    }

    /**
     * 获取类目详细信息
     */
    @ApiOperation(value="获取类目详细信息")
    @PreAuthorize("@ss.hasPermi('mall:category:query')")
    @PostMapping(value = "/getInfo")
    public HttpResult<MallCategory> getInfo(@RequestBody   ReqIdParam id) {
        return HttpResult.ok(mallCategoryService.selectMallCategoryById(id));
    }

    /**
     * 新增类目
     */
    @ApiOperation(value="新增商城商品类目")
    @PreAuthorize("@ss.hasPermi('mall:category:add')")
    @Log(title = "商品管理>商品分类", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public HttpResult<Boolean> add(@RequestBody  MallCategory mallCategory) {
        MallCategory one = mallCategoryService.lambdaQuery().eq(MallCategory::getId, mallCategory.getPid()).one();
        if (one != null) {
            Long type = one.getType();
            if (type != null) {
                mallCategory.setType(type);
            }
        }
        return to(mallCategoryService.insertMallCategory(mallCategory));
    }

/*    @ApiOperation(value="新增店铺商品类目")
    @PreAuthorize("@ss.hasPermi('mall:category:storeAdd')")
    @Log(title = "商品管理>店铺商品分类", businessType = BusinessType.INSERT)
    @PostMapping(value = "/storeAdd")
    public HttpResult<Boolean> storeAdd(@RequestBody  MallCategory mallStoreCategory) {
        return to(mallCategoryService.insertMallStoreCategory(mallStoreCategory));
    }*/

    /**
     * 修改类目
     */
    @ApiOperation(value="修改类目")
    @PreAuthorize("@ss.hasPermi('mall:category:edit')")
    @Log(title = "商品管理>商品分类", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public HttpResult<Boolean> edit(@RequestBody  MallCategory mallCategory) {
        MallCategory one = mallCategoryService.lambdaQuery().eq(MallCategory::getId, mallCategory.getPid()).one();
        if (one != null) {
            Long type = one.getType();
            if (type != null) {
                mallCategory.setType(type);
            }
        }
        return to(mallCategoryService.updateMallCategory(mallCategory));
    }

    /**
     * 删除类目
     */
    @ApiOperation(value="删除类目")
    @PreAuthorize("@ss.hasPermi('mall:category:remove')")
    @Log(title = "商品管理>商品分类", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
    public HttpResult remove(@RequestBody  ReqIdsParam ids) {
        int count = mallGoodsService.count(new LambdaQueryWrapper<MallGoods>().eq(MallGoods::getCategoryId, ids.getId().get(0)));
        if (count > 0) {
            return HttpResult.error("该分类下有商品禁止删除！");
        }
        count = mallCategoryService.count(new LambdaQueryWrapper<MallCategory>().eq(MallCategory::getPid, ids.getId().get(0)));
        if (count > 0) {
            return HttpResult.error("该分类含有子分类禁止删除！");
        }
        mallCategoryService.deleteMallCategoryByIds(ids);
        return HttpResult.ok();
    }

    @ApiOperation(value = "获取商城顶级分类")
    @PreAuthorize("@ss.hasAnyPermi('mall:category:list,mall:goods:list,mall:goods:add,mall:goods:edit,mall:supplier-goods:list,')")
    @PostMapping("/listParent")
    public HttpResult<List<MallCategory>> listParent(){
        return HttpResult.ok(mallCategoryService.listPatent());
    }

    @ApiOperation(value = "获取店铺顶级分类")
    @PreAuthorize("@ss.hasAnyPermi('mall:category:list,mall:goods:list,mall:goods:add,mall:goods:edit,mall:supplier-goods:list,')")
    @PostMapping("/listStoreParent")
    public HttpResult<List<MallCategory>> listStoreParent(){
        return HttpResult.ok(mallCategoryService.listStoreParent());
    }


    @PreAuthorize("@ss.hasAnyPermi('mall:category:list,mall:goods:list,mall:goods:add,mall:goods:edit,mall:supplier-goods:edit,mall:supplier-goods:add')")
    @PostMapping("/listChild")
    public HttpResult<List<MallCategory>> listChild(@RequestBody ReqIdParam reqIdParam){
        return HttpResult.ok(mallCategoryService.listChild(reqIdParam));
    }

    @PostMapping("/listStoreChild")
    public HttpResult<List<MallCategory>> listStoreChild(@RequestBody ReqIdParam reqIdParam){
        return HttpResult.ok(mallCategoryService.listStoreChild(reqIdParam));
    }

    /*****
     *  将当前分类的排序减1 顺序上升一位
     * @param mallCategory
     * @return
     */
    @PostMapping("/reSortOrderReduce")
    public HttpResult<Boolean> reSortOrderReduce(@RequestBody MallCategory mallCategory){
        return HttpResult.ok(mallCategoryService.reSortOrderReduce(mallCategory));
    }

    /*****
     * 将当前分类的排序加1 顺序下降一位
     * @param mallCategory
     * @return
     */
    @PostMapping("/reSortOrderPlus")
    public HttpResult<Boolean> reSortOrderPlus(@RequestBody MallCategory mallCategory){
        return HttpResult.ok(mallCategoryService.reSortOrderPlus(mallCategory));
    }
}
